package ecustom.clients.util;

import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtil {
	
	private final static Logger log = Logger.getLogger(JsonUtil.class);
	
	private static ObjectMapper mapper = new ObjectMapper();
	static {
		mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	}

	public static String toJson(Object obj) {
		try {
			return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			log.error(e.toString(), e);
		}
		return "{}";
	}

	public static <T> T fromJson(StringBuilder json, Class<T> clazz) throws Exception {
		return fromJson(json.toString(), clazz);
	}

	public static <T> T fromJson(String json, Class<T> clazz) throws Exception {
		return mapper.readValue(json, clazz);
	}
	
	public static <T> List<T> listFromJson(String json, Class<T> clazz) throws Exception {
		return mapper.readValue(json, new TypeReference<List<T>>(){});
	}
	
	public static List<Map<String, Object>> listMapFromJson(String json) throws Exception {
		return mapper.readValue(json, new TypeReference<List<Map<String, Object>>>(){});
	}
	
	public static Map<String, Object> toMap(String json) throws Exception {
		return mapper.readValue(json, new TypeReference<Map<String, Object>>(){});
	}
}